﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using EPiServer;
using EPiServer.Core;
using EPiServer.ServiceLocation;
using EPiServer.Web.Routing;

namespace EPiBoost.Core.Extensions.Html
{
	public static class CurrentPageExtensions
	{
		public static PageData GetCurrentPage(this HtmlHelper htmlHelper, IContentLoader contentLoader = null)
		{
			contentLoader = contentLoader ?? ServiceLocator.Current.GetInstance<IContentLoader>();
			var languageName = htmlHelper.ViewContext.RequestContext.GetLanguage();
			var languageSelector = LanguageSelector.Fallback(languageName, true);
			var currentNode =  contentLoader.Get<IContent>(htmlHelper.ViewContext.RequestContext.GetContentLink(), languageSelector);

			return currentNode.GetPage();
		}

		public static T GetCurrentPage<T>(this HtmlHelper htmlHelper, IContentLoader contentLoader = null) where T : PageData
		{
			contentLoader = contentLoader ?? ServiceLocator.Current.GetInstance<IContentLoader>();
			var languageName = htmlHelper.ViewContext.RequestContext.GetLanguage();
			var languageSelector = LanguageSelector.Fallback(languageName, true);
			var currentNode = contentLoader.Get<IContent>(htmlHelper.ViewContext.RequestContext.GetContentLink(), languageSelector);

			return (T) currentNode.GetPage<T>();
		}
		 
	}
}
